import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";
import { ref } from "vue";
import { useTokenStore } from '@/stores/token';

//返回的是Axios实例
const service = axios.create({
    baseURL: 'http://localhost:8080'
    
});


//Axios 请求的拦截器
service.interceptors.request.use(function (config) {
    const tokenStore=useTokenStore();
    //如果不是登录请求就要在请求头添加token
    if (!config.url.startsWith("/login")) {
        config.headers.token = tokenStore.tokenStr;
        
    }
    return config;
}, function (error) {
    //对请求错误做些什么
    return Promise.reject(error);
});
//Axios 响应拦截器
service.interceptors.response.use(resp => {
    const tokenStore=useTokenStore();
    //获得续期的jwt
    let token=resp.headers.token;
    //放入sessionStorage
    tokenStore.update(token);
    return resp.data;
}, error => {
    if (error.status == 403) {
        ElMessage.error({
            message: '令牌错误，请重新登录',
            duration: 1200,
            onClose: () => {
                //提示信息消失的回调
                //删除sessionStorage中的token
                
                const tokenStore=useTokenStore();
                tokenStore.$reset();
                //跳转到登录页
                router.push('/login');

            }

        });
    }
});
 
export default service;


